<template>
  <div class="simple-upload">
    <h3>文件上传</h3>

    <!-- 上传区域 -->
    <div class="upload-area" @click="selectFile">
      <span>点击选择文件</span>
      <input type="file" ref="fileInput" @change="handleFileChange" class="file-input" />
    </div>

    <!-- 选中文件信息 -->
    <div v-if="selectedFile" class="file-info">
      <p>文件名: {{ selectedFile.name }}</p>
      <p>大小: {{ formatSize(selectedFile.size) }}</p>

      <!-- 上传按钮和进度 -->
      <button @click="upload" :disabled="isUploading">
        {{ isUploading ? "上传中..." : "上传" }}
      </button>

      <!-- 进度条 -->
      <div v-if="isUploading" class="progress">
        <div class="progress-bar" :style="{ width: progress + '%' }"></div>
        <span>{{ progress }}%</span>
      </div>

      <!-- 结果提示 -->
      <p v-if="uploadSuccess" class="success">上传成功!</p>
      <p v-if="uploadError" class="error">上传失败，请重试</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedFile: null,
      isUploading: false,
      progress: 0,
      uploadSuccess: false,
      uploadError: false,
    };
  },
  methods: {
    // 触发文件选择
    selectFile() {
      this.$refs.fileInput.click();
    },

    // 处理文件选择
    handleFileChange(e) {
      if (e.target.files.length) {
        let file = this.selectedFile = e.target.files[0];
        this.uploadSuccess = false;
        this.uploadError = false;
        const reader = new FileReader();

        // 读取为ArrayBuffer（二进制缓冲区）
        reader.readAsArrayBuffer(file);

        reader.onload = function (e) {
          // 获取二进制缓冲区
          const arrayBuffer = e.target.result;
          // console.log("文件大小（字节）:", arrayBuffer.byteLength);

          // 转换为Uint8Array（可直接操作的二进制数组）
          const binaryData = new Uint8Array(arrayBuffer);
          console.log("二进制数据流:", binaryData);

          // 示例：取前10个字节查看
          // console.log("前10字节:", binaryData.subarray(0, 10));
        };
      }
    },

    // 上传文件
    upload() {
      if (!this.selectedFile) return;

      this.isUploading = true;
      this.uploadSuccess = false;
      this.uploadError = false;
      this.progress = 0;

      // 模拟上传过程
      const interval = setInterval(() => {
        this.progress += 10;

        if (this.progress >= 100) {
          clearInterval(interval);
          this.isUploading = false;
          // 随机模拟成功/失败
          this.uploadSuccess = Math.random() > 0.2;
          this.uploadError = !this.uploadSuccess;
        }
      }, 300);

      // 实际项目中替换为真实接口调用
      /*
      const formData = new FormData();
      formData.append('file', this.selectedFile);
      
      axios.post('/upload', formData, {
        onUploadProgress: (e) => {
          this.progress = Math.round((e.loaded / e.total) * 100);
        }
      }).then(() => {
        this.uploadSuccess = true;
        this.isUploading = false;
      }).catch(() => {
        this.uploadError = true;
        this.isUploading = false;
      });
      */
    },

    // 格式化文件大小
    formatSize(bytes) {
      if (bytes < 1024) return bytes + " B";
      if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB";
      return (bytes / 1048576).toFixed(1) + " MB";
    },
  },
};
</script>

<style scoped>
.simple-upload {
  max-width: 500px;
  margin: 2rem auto;
  padding: 1rem;
}

.upload-area {
  border: 2px dashed #ccc;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  margin-bottom: 1rem;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #42b983;
}

.file-input {
  display: none;
}

.file-info {
  margin-top: 1rem;
  padding: 1rem;
  border: 1px solid #eee;
}

button {
  margin: 1rem 0;
  padding: 0.5rem 1rem;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.progress {
  height: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  overflow: hidden;
  margin: 0.5rem 0;
  position: relative;
}

.progress-bar {
  height: 100%;
  background: #42b983;
  transition: width 0.3s;
}

.progress span {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 0.8rem;
}

.success {
  color: #42b983;
}

.error {
  color: #ff4444;
}
</style>
